package myauctioneer.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import myauctioneer.App;
import myauctioneer.dto.Bid;

public class BidDAO implements BidDAOI {

	private PreparedStatement saveStmt;
	private PreparedStatement loadStmt;
	private PreparedStatement loadStmtByArticle;
	
	public BidDAO() {
		try {
			saveStmt = App
					.getDb()
					.prepareStatement(
							"INSERT INTO bid(customer_id, item_id, time, amount) "
									+ "VALUES (?, ?, CURRENT_DATE, ?)");

			loadStmt = App.getDb().prepareStatement(
					"SELECT * FROM bid " + "WHERE bid_id = ?");

			loadStmtByArticle = App.getDb().prepareStatement(
					"SELECT * FROM bid WHERE item_id = ? ORDER BY time");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void saveBid(Bid b) {
		try {
			saveStmt.setInt(1, b.getUserId());
			saveStmt.setInt(2, b.getArticleId());
			saveStmt.setDouble(3, b.getAmount());

			if(saveStmt.executeUpdate() == 0)
				throw new SQLException("Cannot save bid.");

			ResultSet rs = App.getDb().createStatement()
				.executeQuery("SELECT SEQUENCE_BID_ID.CURRVAL FROM dual");

			if(rs.next())
				b.setBidId(rs.getInt(1));
			else
				throw new SQLException("Cannot save bid.");

		} catch (SQLException e) {
			App.getLogger().log(java.util.logging.Level.WARNING, e.getMessage(), e);
			e.printStackTrace();
		}
	}

	@Override
	public Bid loadBidByBidId(int bidId) {
		Bid b = null;
		try {
			loadStmt.setInt(1, bidId);
			ResultSet result = loadStmt.executeQuery();
			if (result.next())
				b = this.load(result);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return b;
	}

	protected Bid load(ResultSet result) throws SQLException {
		Bid b = new Bid();

		b.setBidId(result.getInt("bid_id"));
		b.setArticleId(result.getInt("item_id"));
		b.setUserId(result.getInt("customer_id"));
		b.setTime(result.getString("time"));
		b.setAmount(result.getDouble("amount"));

		return b;
	}

	@Override
	public ArrayList<Bid> loadBidByArticleId(int article) {
		ArrayList<Bid> bids = new ArrayList<Bid>();

		try {
			loadStmtByArticle.setInt(1, article);
			ResultSet result = loadStmtByArticle.executeQuery();

			while(result.next())
				bids.add(this.load(result));
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bids;
	}
}
